<?php

/*
 * 商家模型
 * @author wyb
 */

namespace Qwadmin\Model;

class ShgApiModel extends ApiModel {

    var $token = '7a8ee1cf676343a3726279bfeca0446b9ee9f7831d1fce6c744baff4ee947cf7';
    var $baseparams = array(
        'direct' => 'true', // 
        'app_id' => 'b2c',
        'pass' => "24a93034b3430dfa8ff50fa3f036cfe4",
    );

    //获取分类信息
    public function getcatlist($indata) {


        // var_dump($this->api); 
        $basic_params = array(
            'direct' => 'true', // 
            'method' => 'b2c.goods.get_cat',
            'app_id' => 'b2c',
            'date' => date('Y-m-d H:m:s', time()),
            'page_no' => 1,
            'page_size' => 999,
        );
        $params = array_merge($this->baseparams, $basic_params);


        $params['sign'] = self::get_sign($params, $this->token);
        $url = $this->url;



        $result = json_decode($this->post($url, $params));


        //var_dump($result->data->datas);
        if ($result->rsp == 'succ') {
            $modelsType = M('shop_types');
            foreach ($result->data->datas as $k => $v) {

                $catdata = array();
                $catdata['shop_sites_id'] = $this->api['shop_id'];
                $catdata['name'] = $v->cat_name;
                $catdata['shop_type_id'] = $v->cat_id;
                $catdata['pid'] = $v->pid;
                $catdata['path'] = $v->cat_path;

                $where['shop_sites_id'] = $this->api['shop_id'];
                $where['shop_type_id'] = $v->cat_id;

                $id = $modelsType->where($where)->getField("id");

                if ($id) {
                    $modelsType->where(array('id' => $id))->save($catdata);
                } else {
                    $modelsType->data($catdata)->add();
                }
            }
            echo "导入成功";
        }
    }

    //获取商品品牌信息
    public function getbrandlist($indata) {

        $basic_params = array(
            'method' => 'b2c.goods.get_brands',
            'date' => date('Y-m-d H:m:s', time()),
            'page_no' => 1,
            'page_size' => 9999,
        );
        $params = array_merge($this->baseparams, $basic_params);

        $params['sign'] = self::get_sign($params, $this->token);
        $url = $this->url;



        $result = json_decode($this->post($url, $params), true);

        if ($result['data']['datas']) {
            $rr = $result['data']['datas'];
            $model = M("goods_brand");
            $model->where("1=1")->delete();
            foreach ($rr as $r) {
                $temp['id'] = $r['brand_id'];
                $temp['name'] = $r['brand_chinese_name'] ? $r['brand_chinese_name'] : $r['brand_name'];
                $temp['info'] = $r['brand_desc'];
                $model->add($temp);
            }

            echo "添加成功";
        }
    }

    //获取分类信息
    public function get_all_list($pagesize = 1,$site_id=10001) {

        $time1= $this->getmtime();

		if($this->api['shop_id'])$site_id=$this->api['shop_id'];
		echo $site_id;
		
        if (isset($_GET['pg']))
            $pagesize = (int) $_GET['pg'] ? (int) $_GET['pg'] : 1;

        $basic_params = array(
            'method' => 'b2c.goods.get_all_list',
            'date' => date('Y-m-d H:m:s', time()),
            'brand_id' => 0,
            'cat_id' => 0,
            'cid' => 0,
            'page_no' => $pagesize,
            'page_size' => 5,
        );

        $params = array_merge($this->baseparams, $basic_params);


        $params['sign'] = self::get_sign($params, $this->token);
        $url = $this->url;



        $result = json_decode($this->post($url, $params));
         echo ($this->getmtime()-$time1)."ms";
        //var_dump($result);
        if ($result->rsp == 'succ') {
            $items = json_decode($result->data->items);
            // var_dump($items);

            $goods=M('goods');
			$goodstatus=M('goods_status');
            foreach ($items->item as $k => $v) {

                foreach ($v->image_arr as $ik => $img) {
                    // var_dump($img);
                    //echo "<img src=".$img->url."  alt=".$img->image_name ."  />";
                }
				//var_dump($v);die();
                $pdata = array();
                $pdata['name'] = $v->title;
                $pdata['sku'] = $v->bn;
                $pdata['goods_brand_id'] = $v->brand_id;
                $pdata['price_cost'] = $v->cost_price;
                $pdata['price_market'] = $v->market_price;
                $pdata['price'] = $v->price;
                $pdata['made_in'] = $v->country_id;
                //$pdata['price_cost'] = $v->cat_path;
                $pdata['pom'] = $v->unit;
                $pdata['weight'] = $v->weight;
                $pdata['stock_num'] = $v->num;
                $pdata['info_pc'] = $v->description;
                $pdata['goods_type_id'] = '1000000' . $v->shop_cids;

               // echo $v->marketable;
			    if(strlen($pdata['sku'])<5){ echo "error sku";continue;} 
				$gs=$goods->where("sku='".$pdata['sku']."'")->find();
				//echo $gs['id'];
                if(!$gs) 
				{
				    $goods->data($pdata)->add();
				}else
				{
					$r=$goods->where("sku='".$pdata['sku']."'")->save($pdata);
					///更新在线数据状态
					$gd=$goodstatus->where('goods_id='.$gs['id'].' and site_id='.$site_id)->find();
					if(!$gd)
					{
						$status=array();
						$status['goods_id']=$gs['id'];
						$status['site_id']=$site_id;
						$status['status']=($v->marketable=='false')?0:1;
						$goodstatus->data($status)->add();
					}else
					{
						////
						$sd=unserialize($gd['status']);
						
						$newgs['goods_id']=$gs['id'];
						$newgs['site_id']=$site_id;
						$newgs['status']=($v->marketable=='false')?0:1;
				        $goodstatus->where('goods_id='.$gs['id'].' and site_id='.$site_id)->save();
					}
					
				}
                //if (strpos($err->getMessage(), 'Duplicate entry') > 0) {$erri++; }

                }
            }
			echo ($this->getmtime()-$time1)."ms";
            ////if($err){echo "导入成功，共".$erri."条重复<br>";	}else{echo "导入成功！";};	
           
            if ($result->data->total_results > ($basic_params['page_no'] * $basic_params['page_size'])) {
                echo "here:" . $basic_params['page_no'] . "<br>";
                $nextpage = $basic_params['page_no'] + 1;
				echo '<script type="text/javascript">';

                echo 'function nextpage() {location.href="'. U('runapi',array('apiid'=>5,'pg'=>$nextpage)).'";}';
				echo 'setTimeout(nextpage(),2000);';
                //self::get_all_list($basic_params['page_no']+1);
				echo "</script>";
            }
       
    }

   public function ws_test($indata)
   {
	    
        $basic_params = array(
            'method' => 'b2c.goods.wstest',
        );
        $params = array_merge($this->baseparams, $basic_params);

        $params['sign'] = self::get_sign($params, $this->token);
        $url = $this->url;
        $result = json_decode($this->post($url, $params));
	    
		if($result->rsp=='succ')
		{
			
			foreach($result->data as $dt)
			{
				
				//echo "vist url :";
	
		        echo "http://www.shenghuigo.com/product-".$dt->goods_id."-".$dt->store_id.".html";	
				echo "<br>";
				
			}
			
		}
	

			var_dump($result);
		 
 
   }
    //自动组合入库数据
    public function getb2bcatlist($indata) {

        echo "123";
        var_dump($this->api['shop_id']);
        $basic_params = array(
            'method' => 'b2c.goods.get_cat',
            'date' => date('Y-m-d H:m:s', time()),
            'page_no' => 1,
            'page_size' => 999,
        );

        $params = array_merge($this->baseparams, $basic_params);


        $params['sign'] = self::get_sign($params, $this->token);
        $url = $this->url;

        $result = json_decode($this->post($url, $params));

        //var_dump($result->data->datas);
        if ($result->rsp == 'succ') {
            $modelsType = M('shop_types');
            foreach ($result->data->datas as $k => $v) {

                $catdata = array();
                $catdata['shop_sites_id'] = $this->api['shop_id'];
                $catdata['name'] = $v->cat_name;
                $catdata['shop_type_id'] = $v->cat_id;
                $catdata['pid'] = $v->pid;
                $catdata['path'] = $v->cat_path;

                $where['shop_sites_id'] = $this->api['shop_id'];
                $where['shop_type_id'] = $v->cat_id;

                $id = $modelsType->where($where)->getField("id");

                if ($id) {
                    $modelsType->where(array('id' => $id))->save($catdata);
                } else {
                    $modelsType->data($catdata)->add();
                }
            }
            echo "导入成功";
        }
    }

    public function test() {

        echo "test";
    }

    function get_all_store() {
//        var_dump($this->api['shop_id']); 
        $basic_params = array(
            'method' => 'b2c.goods.get_all_store',
            'date' => date('Y-m-d H:m:s', time()),
            'page_no' => 1,
            'page_size' => 999,
        );
        $params = array_merge($this->baseparams, $basic_params);
        $params['sign'] = self::get_sign($params, $this->token);
        $str = $this->post($this->url, $params);
        $result = json_decode($str, true);
        var_dump($result);
        if ($result['data']) {
            //先暂时插入本地临时数据
//            $partaner_Mdoel=M("partner");
//            foreach ($result['data'] as $key => $value) {
//                $data['name']=$value['store_name'];
//                $data['trade']=$value['store_name'];
//                $data['owner']=$value['company_idname'];
//                $data['tel']=$value['tel'];
//                $data['status'] = $value['status'];
//                $data['exp_time'] = $value['company_timeend'];
//                $partaner_Mdoel->add($data);
//            }



            $partaner_stMdoel = M("partner_store");
            $partaner_stMdoel->startTrans();
            foreach ($result['data'] as $key => $value) {
                $stores = $partaner_stMdoel->where(array('store_id' => $value['store_id'], 'shop_id' => $this->api['shop_id']))->find();

                $data = array(
                    'name' => $value['store_name'],
                    'store_id' => $value['store_id'],
                    'shop_id' => $this->api['shop_id'],
                );
                if ($stores) {
                    $insertflag = $partaner_stMdoel->where(array("id" => $stores['id']))->save($data);
                } else {
                    $insertflag = $partaner_stMdoel->add($data);
                }
                if ($insertflag === false) {
                    $partaner_stMdoel->rollback();
                    echo "数据插入失败";
                    die;
                }
            }
            $partaner_stMdoel->commit();
            echo '操作成功';
        } else {
            echo "no data!";
        }
    }

    /**
     * 添加商品信息到合作站点
     * 
     *             
      //参数	类型	是否必须	说明
      //
      //type_id	Number	Y	商品类型(参数不传，默认为:1,表示通用商品类型)
      //cat_id	Number	N	商品分类(参数不传，默认为:0,表示分类不限)
      //brief	String	N	简介
      //description	String	N	描述
      //brand_id	Number	N	商品品牌
      //cost	Number	N	商品成本价
      //price	Number	N	商品价格
      //mktprice	Number	N	商品市场价
      //weight	Number	N	商品重量
      //num	Number	N	商品数量
      //score	Number	N	商品积分
      //unit	String	N	计件单位
      //approve_status	String	N	是否上下架(上架：onsale,其他均未下架)
      //is_simple	Boolean	N	是否为简单商品；可选值：true，false （如为true ，则返回sku_id）
      //image_default_id	String	N	商品主图url路径，目前只支持gif,jpg,png,bmp格式，地址为远程http地址
      //props	String	N	商品属性串 pid:vid;pid:vid;pid:vid;pid:vid
      //input_pids	String	N	用户输入的自定义属性 pid;pid;pid;pid;pid;pid;pid
      //input_str	String	N	用户输入的自定义属性值 value;value;value;value;value
      //sku_bns	String	N	货品货号 json_encode(array('10','15','20'))
      //sku_store	String	N	货品库存 json_encode(array('EA001','EA002','EA003'))
      //sku_prices	String	N	货品价格 json_encode(array('21.00','21.00','23.00'))
      //sku_costs	String	N	货品成本价 json_encode(array('10.00','12.00','14.00'))
      //sku_mktprices	String	N	货品市场价 json_encode(array('30.00','40.00','50.00'))
      //sku_weights	String	N	货品重量 json_encode(array('1.00','2.00','3.00'))
      //sku_properties	String	if(sku_bns!=''){Y}else{N}	商品规格串 pid:vid_pid:vid_pid:vid;pid:vid_pid:vid_pid:vid,如果开启多货品，此参数必填
      //related_items	String	N	相关商品 json_encode(array('31','106','117'))
      //keywords	String	N	关键字 json_encode(array('女鞋','时尚秋季女鞋','羊皮女鞋'))

     * */
    function addgoodssite($goods_id, $shop_id, $store_id, $optype = "add") {

        $returns = array("rsp" => 'error', "log" => '', 'optime' => time());

        $goods_model = D("Goods");
        $goods = $goods_model->init_goods($goods_id);
        if(!$goods){
            $returns['log'] = "商品未找到";
            return $returns;
        }
        $store_id_real = $goods_model->getRealStore_id($store_id, $shop_id);
        $code = M("partner")->where(array('id' => $store_id))->getField("trade");
        $code = $code ? $code : $goods['trade_type'];
        $trade = $goods_model->gettradeid($code, $shop_id);

        if (!$goods) {
            $returns['log'] = "商品没找到";
            return $returns;
        }
        file_put_contents("./Public/2222", print_r($goods,true));
        $type_id = $goods['type_info_key'][$shop_id];
//        if (!$type_id) {
//            $returns['log'] = "商品真正的分类没找到";
//            return $returns;
//        }

        $basic_params = array(
            'method' => 'b2c.goods.add',
            'store_id' => $store_id_real,
            'bn' => $goods['sku'],
            'name' => $goods['name'],
            'cat_id' => $type_id, //洗发
            'brief' => $goods['info_notice'],
            'description' => $goods['info_pc'],
            'brand_id' => $goods['goods_brand_id'], //判断是字段类型 要是int 就直接写入 要是是字符串  就转换成ID  415  宝制果
            'cost' => $goods['price_cost'],
            'price' => $goods['price'],
            'mktprice' => $goods['price_market'],
            'weight' => $goods['weight'],
            'num' => $goods['stock_num'], //数量   总
            'sku_store' => json_encode(array($goods['stock_num'])), //数量  分   之和等于num
            'unit' => $goods['pom'], //计件单元
            'approve_status' => "onsale", //是否上下架(上架：onsale,其他均未下架)
            'is_simple' => true,
            'image_default_id' => $goods['pic_thumb'],
            'pic_list' => json_encode(json_decode($goods['pic_list'])),
            'keywords' => json_encode(json_decode($goods['info_keywords'])),
            'country_id' => $goods['made_in'],
            'goods_mode' => $trade,
            'taxes_no' => $goods['tax_no'],
            'excise_taxes' => $goods['tax_xf'],
            'customs_taxes' => $goods['tax_gw'],
            'added_value_taxes' => $goods['tax_added'],
            'die_time' => $goods['die_time'],//过期时间 default null
            'markstr' => $goods['extra_info'],//过期时间 default null
        );
        $params = array_merge($this->baseparams, $basic_params);


        if ($optype == "update") { //如果是更新
            $params['method'] = 'b2c.goods.update';
        }        
        $params['sign'] = self::get_sign($params, $this->token);
        
        $str = $this->post($this->url, $params);
        $result = json_decode($str, true);
        if ($result['rsp'] == 'fail') {
            $returns['log'] = "添加失败 " . $result['res'];
            return $returns;
        } else {
            $returns['log'] = "添加成功 ";
            $returns['rsp'] = "succ";
            return $returns;
        }
    }

    /**
     * 更新商品
     * @param type $goods_id
     * @param type $shop_id
     * @param type $store_id
     * @return type
     */
    function updategoods($goods_id, $shop_id, $store_id) {
        return $this->addgoodssite($goods_id, $shop_id, $store_id, "update");
    }

    function goodsDown($goods_id, $shop_id, $store_id) {
        $returns = array("rsp" => 'error', "log" => '', 'optime' => time());
        $goods_model = D("Goods");
        $goods = $goods_model->init_goods($goods_id);
        if(!$goods){
            $returns['log'] = "商品未找到";
            return $returns;
        }
//        $store_id_real = $goods_model->getRealStore_id($store_id, $shop_id);
        $basic_params = array(
            'method' => 'b2c.goods.goods_marketable',
            'store_id' => "0",
            'bn' => $goods['sku'],
            'marketable' => 'false',
        );
        $params = array_merge($this->baseparams, $basic_params);

        $params['sign'] = self::get_sign($params, $this->token);
        $str = $this->post($this->url, $params);
        echo $str;
        $ress = json_decode($str, true);
        if ($ress['rsp'] == "succ") {
            $returns['rsp'] = "succ";
        }
        return $returns;
    }

    function goodsOnline($goods_id, $shop_id, $store_id) {
        $returns = array("rsp" => 'error', "log" => '', 'optime' => time());
        $goods_model = D("Goods");
        $goods = $goods_model->init_goods($goods_id);
        if(!$goods){
            $returns['log'] = "商品未找到";
            return $returns;
        }
        $store_id_real = $goods_model->getRealStore_id($store_id, $shop_id);
        $basic_params = array(
            'method' => 'b2c.goods.goods_marketable',
            'store_id' => $store_id_real,
            'bn' => $goods['sku'],
            'marketable' => 'true',
        );
        $params = array_merge($this->baseparams, $basic_params);
        $params['sign'] = self::get_sign($params, $this->token);

        $str = $this->post($this->url, $params);
        $ress = json_decode($str, true);
        if ($ress['rsp'] == "succ") {
            $returns['rsp'] = "succ";
        }
        return $returns;
    }

    /***
     * 价格变更
     */
    function goodsPriceUpdate($goods_id, $shop_id, $store_id) {
        $returns = array("rsp" => 'error', "log" => '', 'optime' => time());
        $goods_model = D("Goods");
        $goods = $goods_model->init_goods($goods_id);
        if(!$goods){
            $returns['log'] = "商品未找到";
            return $returns;
        }
//        $store_id_real = $goods_model->getRealStore_id($store_id, $shop_id);
        $basic_params = array(
            'method' => 'b2c.goods.goods_price_update',
            'bn' => $goods['sku'],
            'price' => $goods['price'],
            'mktprice' => $goods['price_market'],
        );
        $params = array_merge($this->baseparams, $basic_params);

        $params['sign'] = self::get_sign($params, $this->token);
        print_r($params);
        echo "<br>";
        $str = $this->post($this->url, $params);
        $ress = json_decode($str, true);
        if ($ress['rsp'] == "succ") {
            $returns['rsp'] = "succ";
        }
        return $returns;
    }
    
    /***
     * 库存变更
     */
    function goodsStockUpdate($goods_id, $shop_id, $store_id) {
        $returns = array("rsp" => 'error', "log" => '', 'optime' => time());
        $goods_model = D("Goods");
        $goods = $goods_model->init_goods($goods_id);
        if(!$goods){
            $returns['log'] = "商品未找到";
            return $returns;
        }
//        $store_id_real = $goods_model->getRealStore_id($store_id, $shop_id);
        $basic_params = array(
            'method' => 'b2c.goods.goods_stock_update',
            'bn' => $goods['sku'],
            'stock' => $goods['stock_num'],
        );
        $params = array_merge($this->baseparams, $basic_params);

        $params['sign'] = self::get_sign($params, $this->token);
        print_r($params);
        echo "<br>";
        $str = $this->post($this->url, $params);
        $ress = json_decode($str, true);
        if ($ress['rsp'] == "succ") {
            $returns['rsp'] = "succ";
        }
        return $returns;
    }

    public static function get_sign($params, $token = "") {
        return strtoupper(md5(strtoupper(md5(self::assemble($params)))));
    }

    public static function assemble($params) {
        if (!is_array($params))
            return null;
        ksort($params, SORT_STRING);
        $sign = '';
        foreach ($params AS $key => $val) {
            if (is_null($val))
                $val = '';
            if (is_bool($val))
                $val = ($val) ? 1 : 0;
            $sign .= $key . (is_array($val) ? self::assemble($val) : $val);
        }
        return $sign;
    }

//End Function
}
